package cn.edu.buu.hospital.service.impl;

import cn.edu.buu.hospital.entity.Department;
import cn.edu.buu.hospital.entity.Doctor;
import cn.edu.buu.hospital.entity.Hospital;
import cn.edu.buu.hospital.entity.Visit;
import cn.edu.buu.hospital.mapper.DepartmentMapper;
import cn.edu.buu.hospital.mapper.DoctorMapper;
import cn.edu.buu.hospital.mapper.VisitMapper;
import cn.edu.buu.hospital.service.DepartmentService;
import cn.edu.buu.hospital.service.HospitalService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;
    
    @Autowired
    private DoctorMapper doctorMapper;

    @Autowired
    private VisitMapper visitMapper;

    @Autowired
    private HospitalService hospitalService;
    @Override
    public void add(Department department) {
        // 表单验证
        if (department == null) {
            throw new RuntimeException("科室信息不能为空");
        }
        if (department.getHospitalid() == null) {
            throw new RuntimeException("请选择所属医院");
        }
        if (department.getDeptname() == null || department.getDeptname().trim().isEmpty()) {
            throw new RuntimeException("科室名称不能为空");
        }
        if (department.getIllness() == null) {
            department.setIllness("");
        }
        if (department.getEquipment() == null) {
            department.setEquipment("");
        }
        
        // 检查是否已存在相同医院和科室名称的记录
        Department condition = new Department();
        condition.setHospitalid(department.getHospitalid());
        condition.setDeptname(department.getDeptname());
        List<Department> existing = departmentMapper.selectByCondition(condition);
        if (existing != null && !existing.isEmpty()) {
            throw new RuntimeException("该医院下已存在同名科室，请检查后重试");
        }
        
        departmentMapper.insert(department);
    }

    @Override
    public void removeById(Long deptId) {
        System.out.println("开始删除科室，科室ID: " + deptId);
        
        // 检查科室是否存在
        Department department = departmentMapper.selectById(deptId);
        if (department == null) {
            System.out.println("科室不存在，ID: " + deptId);
            throw new RuntimeException("科室不存在，无法删除");
        }
        System.out.println("找到科室: " + department.getDeptname());
        
        boolean hasRelatedData = false;
        String errorMessage = "";
        
        // 检查是否有关联的医生
        try {
            System.out.println("检查科室关联的医生记录...");
            List<Doctor> doctors = doctorMapper.selectByDeptId(deptId);
            if (doctors != null) {
                System.out.println("找到关联医生数量: " + doctors.size());
                if (!doctors.isEmpty()) {
                    hasRelatedData = true;
                    errorMessage = "该科室下存在医生记录，请先删除相关医生后再尝试删除科室";
                    System.out.println(errorMessage);
                }
            } else {
                System.out.println("医生查询返回null");
            }
        } catch (Exception e) {
            // 记录异常但继续检查其他关联
            System.err.println("检查医生关联时发生异常: " + e.getMessage());
            e.printStackTrace();
        }
        
        // 如果没有医生关联，检查是否有关联的就诊记录
        if (!hasRelatedData) {
            try {
                System.out.println("检查科室关联的就诊记录...");
                // 优先使用selectByDeptId方法，更直接
                List<Visit> visits = visitMapper.selectByDeptId(deptId);
                if (visits != null) {
                    System.out.println("找到关联就诊记录数量: " + visits.size());
                    if (!visits.isEmpty()) {
                        hasRelatedData = true;
                        errorMessage = "该科室下存在就诊记录，请先删除相关记录后再尝试删除科室";
                        System.out.println(errorMessage);
                    }
                } else {
                    System.out.println("就诊记录查询返回null，尝试使用selectByCondition");
                    // 如果selectByDeptId失败或返回null，尝试使用selectByCondition
                    try {
                        Visit visitCondition = new Visit();
                        visitCondition.setDeptId(deptId);
                        visits = visitMapper.selectByCondition(visitCondition);
                        if (visits != null) {
                            System.out.println("通过条件查询找到关联就诊记录数量: " + visits.size());
                            if (!visits.isEmpty()) {
                                hasRelatedData = true;
                                errorMessage = "该科室下存在就诊记录，请先删除相关记录后再尝试删除科室";
                                System.out.println(errorMessage);
                            }
                        }
                    } catch (Exception ex) {
                        // 记录异常但继续执行，不阻止删除
                        System.err.println("检查就诊记录关联时发生异常: " + ex.getMessage());
                        ex.printStackTrace();
                    }
                }
            } catch (Exception e) {
                System.err.println("查询就诊记录时发生异常: " + e.getMessage());
                e.printStackTrace();
            }
        }
        
        // 如果有关联数据，抛出异常
        if (hasRelatedData) {
            System.out.println("删除失败，存在关联数据: " + errorMessage);
            throw new RuntimeException(errorMessage);
        }
        
        // 执行删除操作
        try {
            System.out.println("执行科室删除操作...");
            int result = departmentMapper.deleteById(deptId);
            System.out.println("删除操作结果: " + result);
            if (result == 0) {
                throw new RuntimeException("删除科室失败，可能该科室已被其他操作删除");
            }
            System.out.println("科室删除成功");
        } catch (Exception e) {
            // 检查是否是外键约束异常
            System.err.println("删除科室时发生异常: " + e.getMessage());
            e.printStackTrace();
            if (e.getMessage() != null && (e.getMessage().contains("foreign key constraint") || 
                                           e.getMessage().contains("外键约束"))) {
                throw new RuntimeException("删除失败，该科室可能被其他表引用，请检查并删除相关数据后重试");
            }
            throw new RuntimeException("删除科室时发生系统错误: " + e.getMessage());
        }
    }

    @Override
    public void modify(Department department) {
        // 表单验证
        if (department == null) {
            throw new RuntimeException("科室信息不能为空");
        }
        if (department.getDeptid() == null) {
            throw new RuntimeException("科室ID不能为空");
        }
        if (department.getHospitalid() == null) {
            throw new RuntimeException("请选择所属医院");
        }
        if (department.getDeptname() == null || department.getDeptname().trim().isEmpty()) {
            throw new RuntimeException("科室名称不能为空");
        }
        if (department.getIllness() == null) {
            department.setIllness("");
        }
        if (department.getEquipment() == null) {
            department.setEquipment("");
        }
        
        // 检查科室是否存在
        Department existing = departmentMapper.selectById(department.getDeptid());
        if (existing == null) {
            throw new RuntimeException("科室不存在，无法修改");
        }
        
        // 检查修改后的科室名称在同一医院下是否与其他科室重复
        Department condition = new Department();
        condition.setHospitalid(department.getHospitalid());
        condition.setDeptname(department.getDeptname());
        List<Department> duplicates = departmentMapper.selectByCondition(condition);
        if (duplicates != null && !duplicates.isEmpty()) {
            for (Department dup : duplicates) {
                if (!dup.getDeptid().equals(department.getDeptid())) {
                    throw new RuntimeException("该医院下已存在同名科室，请检查后重试");
                }
            }
        }
        
        departmentMapper.update(department);
    }

    @Override
    public Department findById(Long deptId) {
        Department department = departmentMapper.selectById(deptId);
        // 手动为科室填充医院信息
        if (department != null && department.getHospitalid() != null) {
            try {
                Hospital hospital = hospitalService.findById(department.getHospitalid());
                if (hospital != null) {
                    department.setHospital(hospital);
                }
            } catch (Exception e) {
                // 处理获取医院信息时的异常，不影响科室数据的返回
                System.err.println("获取医院信息失败: " + e.getMessage());
            }
        }
        return department;
    }

    @Override
    public List<Department> findAll(){        
        // 直接从数据库获取所有科室数据
        List<Department> departmentList = departmentMapper.selectAll();
        
        // 手动为每个科室填充医院信息
        if (departmentList != null && !departmentList.isEmpty()) {
            for (Department department : departmentList) {
                if (department != null && department.getHospitalid() != null) {
                    try {
                        Hospital hospital = hospitalService.findById(department.getHospitalid());
                        if (hospital != null) {
                            department.setHospital(hospital);
                        }
                    } catch (Exception e) {
                        // 处理获取医院信息时的异常，不影响科室数据的返回
                        System.err.println("获取医院信息失败: " + e.getMessage());
                    }
                }
            }
        }
        
        // 按科室名称去重，确保下拉列表中不会显示重复的科室名称
        if (departmentList != null && departmentList.size() > 1) {
            List<Department> distinctDepartments = new ArrayList<>();
            // 使用HashSet保存已存在的科室名称
            java.util.Set<String> departmentNames = new java.util.HashSet<>();
            
            for (Department department : departmentList) {
                if (department != null && department.getDeptname() != null && !department.getDeptname().trim().isEmpty()) {
                    String deptName = department.getDeptname().trim();
                    // 如果科室名称尚未存在于set中，则添加
                    if (!departmentNames.contains(deptName)) {
                        departmentNames.add(deptName);
                        distinctDepartments.add(department);
                    }
                }
            }
            
            return distinctDepartments;
        }
        
        return departmentList;
    }

    @Override
    public PageInfo<Department> find(int pageNum, int pageSize, Department condition) {
        PageHelper.startPage(pageNum, pageSize);
        List<Department> departmentList = departmentMapper.selectByCondition(condition);
        // 手动为每个科室填充医院信息
        for (Department department : departmentList) {
            if (department != null && department.getHospitalid() != null) {
                Hospital hospital = hospitalService.findById(department.getHospitalid());
                if (hospital != null) {
                    department.setHospital(hospital);
                }
            }
        }
        return new PageInfo<>(departmentList);
    }

    @Override
    public long findTotal() {
        return departmentMapper.selectTotal();
    }

    @Override
    public List<Department> findTopNum(int i) {
        return departmentMapper.selectTopNum(i);
    }

    @Override
    public List<Department> findByHospitalId(Long hospitalId) {
        Department condition = new Department();
        condition.setHospitalid(hospitalId);
        List<Department> departmentList = departmentMapper.selectByCondition(condition);
        // 手动为每个科室填充医院信息
        for (Department department : departmentList) {
            if (department != null && department.getHospitalid() != null) {
                Hospital hospital = hospitalService.findById(department.getHospitalid());
                if (hospital != null) {
                    department.setHospital(hospital);
                }
            }
        }
        return departmentList;
    }
}